/**
 * Created by mikezhangding on 21/2/2017.
 */
'use strict';


/*app.controller('workCtrl', function ($state, $scope, $http, $localStorage,$ionicSlideBoxDelegate) {


 });*/

angular.module('works.module', [])

  .controller('workCtrl', function ($scope, $state, $ionicHistory, $http) {

    $scope.workList = [];
    $scope.activityList = [];

    $scope.doRefresh=function(){
      $http.get(API("work/reportList")).success(function (result) {
        $scope.workList = result;
      });

      $http.get(API("orgActivity/list/1/100")).success(function (result) {
        $scope.activityList = result;
        $scope.$broadcast('scroll.refreshComplete');
        $scope.$broadcast('scroll.infiniteScrollComplete');
      });
    };

    $scope.doRefresh();

    //控制上报工作tab
    $scope.selected1 = true;
    $scope.selected2 = false;
    $scope.active1 = true;
    $scope.active2 = false;

    $scope.onTabSelected1 = function () {
      $scope.selected2 = false;
      $scope.selected1 = true;
      $scope.active1 = true;
      $scope.active2 = false;
    };
    $scope.onTabSelected2 = function () {
      $scope.selected1 = false;
      $scope.selected2 = true;
      $scope.active1 = false;
      $scope.active2 = true;
    };

  })

  .controller('activityCtrl', function ($scope, $state, $ionicHistory, $http) {

    $scope.activityList = [];

    $scope.doRefresh=function(){

      $http.get(API("orgActivity/list/1/100")).success(function (result) {
        $scope.activityList = result;
        $scope.$broadcast('scroll.refreshComplete');
        $scope.$broadcast('scroll.infiniteScrollComplete');
      });
    };

    $scope.doRefresh();

  })

  .controller('workReportCtrl', function ($scope, $ionicPopup, $http, $stateParams, $ionicActionSheet, $timeout, $state, $ionicLoading, $cordovaImagePicker, Camera, $q,bmap) {

    $scope.image = '';
    $scope.workTime = new Date();
    $scope.report = {workId: $stateParams.workId, location: "定位中.backbutton.backbutton."};


    // bmap.getLocaltion().then(function (data) {
    //   $scope.report.location=data.result.formatted_address;
    //   // console.info(data);
    //   console.info($scope.report.location);
    // },function(error){
    //   $scope.report.location=error;
    // });

    $scope.images = [];

    var items = {'attachments': [], 'images': []};

    $http.get(API("work/reportForm/" + $stateParams.workId)).success(function (result) {
      $scope.work = result.work;
      $scope.items = result.items;

      angular.forEach($scope.items, function (item) {
        if (item.type == 4) {
          item.images = [];
        }
      })
    });


    // 图片选择项
    $scope.showImageUploadChoices = function (item) {
      var hideSheet = $ionicActionSheet.show({
        buttons: [{
          text: '<b>拍照</b> 上传'
        }, {
          text: '从 <b>相册</b> 中选'
        }],
        titleText: '图片上传',
        cancelText: '取 消',
        cancel: function () {
          // add cancel code..
        },
        buttonClicked: function (index) {
          // 相册文件选择上传
          if (index == 1) {
            $scope.readalbum(item);
          } else if (index == 0) {
            // 拍照上传
            $scope.taskPicture(item);
          }
          return true;
        }
      });

    };


    // 读用户相册
    $scope.readalbum = function () {
      if (!window.imagePicker) {
        alert('目前您的环境不支持相册上传。');
        return;
      }

      var options = {
        maximumImagesCount: 3,
        width: 800,
        height: 800,
        quality: 80
      };

      $cordovaImagePicker.getPictures(options).then(function (results) {
        for (var i = 0; i < results.length; i++) {
          console.log('Image URI: ' + results[i]);
          $scope.images.push(results[i]);
        }
      }, function (error) {
        alert(error);
      });
    };

    // 拍照
    $scope.taskPicture = function () {
      if (!navigator.camera) {
        alert('请在真机环境中使用拍照上传。')
        return;
      }

      var options = {
        quality: 85,
        targetWidth: 800,
        targetHeight: 800,
        saveToPhotoAlbum: false
      };
      Camera.getPicture(options).then(function (imageURI) {
        $scope.images.push(imageURI);
      }, function (err) {
        alert("照相机：" + err);
      });

    }

    // 上传到服务器
    $scope.uploadimage = function (uri) {
      var fileURL = uri;
      var options = new FileUploadOptions();
      options.fileKey = "file";
      options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
      options.mimeType = "image/jpeg";
      options.chunkedMode = true;

      var deferred = $q.defer();
      var ft = new FileTransfer();
      ft.upload(fileURL, API('common/upload'), function (data) {
        var resp = JSON.parse(data.response);
        deferred.resolve(resp.data);
      }, function (error) {
        deferred.reject(error);
      }, options);

      return deferred.promise;
    };

    //工作上报提交
    $scope.submitWork = function () {
      $ionicLoading.show({
        template: '上传中...'
      });
      //上传图片
      var promises = [];

      if ($scope.images.length > 0) {
        for (var k = 0; k < $scope.images.length; k++) {
          var p = $scope.uploadimage($scope.images[k]);
          promises.push(p);
        }
        $q.all(promises).then(function (result) {
          console.log(result);
          for (var i = 0; i < result.length; i++) {
            items.images.push(JSON.stringify(result));
          }
          console.log(items);
          submitForm();
        }, function (reson) {
          $ionicLoading.hide();
        });
      } else {
        submitForm();
      }

    };


    function submitForm() {
      $scope.report.itemsJSON = JSON.stringify(items);
      $http.post(API('work/report'), $scope.report).success(function (result) {
        $ionicLoading.hide();
        if (result) {
          var alertPopup = $ionicPopup.alert({
            title: '<h3>提示</h3>',
            template: "提交成功" || ''
          });
          alertPopup.then(function (res) {
            $state.go("tabs.work", {}, {reload: true});
          });
        }
      })
    }

  })

  .controller('orgActivityCtrl', function ($scope, $ionicPopup, $http, $stateParams, $ionicActionSheet, $timeout, $state, $ionicLoading, $cordovaImagePicker, Camera, $q,bmap) {

    $scope.singInTime=new Date();
    $scope.image = '';
    $scope.workTime = new Date();
    $scope.report = {workId: $stateParams.workId, singInLocale: "获取位置中"};

    $scope.images = [];

    // bmap.getLocaltion().then(function (data) {
    //   $scope.report.singInLocale=data.result.formatted_address;
    // },function(error){
    //   $scope.report.singInLocale=error;
    // });

    $http.get(API("orgActivity/" + $stateParams.orgActivityId)).success(function (result) {
      $scope.activity = result;
    });


    //工作上报提交
    $scope.singIn = function () {
      $ionicLoading.show({
        template: '提交中...'
      });
      var data={singInLocale:$scope.report.singInLocale};
      $http.post(API("orgActivity/singIn/"+ $stateParams.orgActivityId),data).success(function (result) {
        $ionicLoading.hide();
        if (result) {
          var alertPopup = $ionicPopup.alert({
            title: '<h3>提示</h3>',
            template: "签到成功" || ''
          });
          alertPopup.then(function (res) {
            $state.go("tabs.work", {}, {reload: true});
          });
        }
      })

    };


  })

  .controller('workHistoryCtrl', function ($scope, $state, $ionicHistory, $http) {
    $scope.currentPage = 1;
    $scope.historys = [];
    $scope.getData = function () {
      $http.get(API("work/history/" + $scope.currentPage)).success(function (result) {
        angular.forEach(result.list, function (h) {
          h.items = JSON.parse(h.itemsJSON);
          for (var i = 0; i < h.items.length; i++) {
            if (h.auditStatus == 0) {
              h.status = '未审核';
            } else {
              if (h.auditResult == 0) {
                h.status = '审核未通过';
              } else {
                h.status = '审核通过';
              }
            }

            if (h.items[i].type == 4 && h.items[i].value) {
              h.items[i].images = JSON.parse(h.items[i].value);
            }
          }
        });

        $scope.historys = result.list;
      })
    };

    $scope.getData();

  })

;




